<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { toggleFullscreen } from '@/utils/fullscreen'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { restartContainerApi, resetContainerApi, saveAnswerReportApi, startTrainingApi } from '@/api/training/training';
import type { UserTrainingResp } from '@/types/training';
import html2pdf from 'html2pdf.js';

const props = defineProps<{
  trainingId: number
}>()

const router = useRouter()

const contentRef = ref() // content元素引用
/**
 * 富文本工具栏配置
 */
const toolbar = ref([
  ['bold', 'italic', 'underline', 'strike'],
  [{ 'color': [] }, { 'background': [] }],         // toggled buttons
  [{ 'align': [] }],
  [{ 'size': ['small', false, 'large', 'huge'] }],
  [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  [{ 'script': 'sub' }, { 'script': 'super' }],
  ['blockquote', 'code-block'],
  ['clean']
])

const userTrainingInfo = ref<UserTrainingResp>()

/**
 * 获取用户实训详情
 */
const findUserTrainingInfo = async () => {
  try {
    const res = await startTrainingApi(props.trainingId)
    userTrainingInfo.value = res.data
    activeDesktop.value = userTrainingInfo.value.containerList[0].containerName
  } catch (error: any) {
    if (error.code === 1002030000) {
      router.push({ name: 'Home' })
    }
  }
}

/**
 * 保存答案
 */
const saveAnswerReport = async () => {

  if (userTrainingInfo.value?.answerReport === undefined) return
  await saveAnswerReportApi({
    trainingId: props.trainingId,
    answerReport: userTrainingInfo.value?.answerReport
  })
  ElMessage({
    message: '提交成功',
    type: 'success'
  })
}

const activeDesktop = ref()

const handleExport = async () => {
  var opt = {
    margin: 1,
    filename: 'myfile.pdf',
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: { scale: 2 },
    jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
  };
  const pdf = await html2pdf().from(userTrainingInfo.value?.answerReport).set(opt).save()
}

// 重启虚拟机确认
const restartHandler = async () => {
  const res = await ElMessageBox.confirm(
    '您确定要重启虚拟机吗？',
    '重启',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  if (res) {
    await restartContainerApi({ userTrainingId: userTrainingInfo.value!.id })
    ElMessage({
      message: '重启成功',
      type: 'success'
    })
  }
}

// 重置虚拟机
const resetHandler = async () => {
  const res = await ElMessageBox.confirm(
    '重置会初始化虚拟机，清空所有数据，您确定要重置吗？',
    '重置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  if (res) {
    await resetContainerApi({ userTrainingId: userTrainingInfo.value!.id })
    ElMessage({
      message: '重置成功',
      type: 'success'
    })
  }
}

onMounted(() => {
  findUserTrainingInfo()
})
</script>

<template>
  <div class="training">
    <div class="common-layout">
      <el-container v-if="userTrainingInfo">
        <el-aside>
          <el-tabs active-name="pdf">
            <el-tab-pane label="实训区" name="pdf">
              <Bc-pdf :src="userTrainingInfo.taskFile" />
            </el-tab-pane>
            <el-tab-pane label="答题区" name="editor">
              <div class="editor">
                <QuillEditor contentType="html" :toolbar="toolbar" v-model:content="userTrainingInfo.answerReport" />
              </div>
              <div class="footer">
                <el-button type="primary" @click="saveAnswerReport">提交</el-button>
                <el-button>重置</el-button>
                <el-button>刷新</el-button>
                <el-button @click="handleExport">导出</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-aside>
        <el-main>
          <div class="content" ref="contentRef">
            <el-tabs v-model="activeDesktop">
              <el-tab-pane v-for="item in userTrainingInfo.containerList" :key="item.containerName"
                :label="item.containerName" :name="item.containerName">
                <bc-vnc v-if="activeDesktop === item.containerName" :port="item.containerPort"
                  :password="item.containerVncPassword" />
              </el-tab-pane>
            </el-tabs>
            <div class="toolbox">
              <el-icon>
                <RefreshLeft @click="restartHandler" />
              </el-icon>
              <el-icon>
                <Refresh @click="resetHandler" />
              </el-icon>
              <el-icon>
                <FullScreen @click="toggleFullscreen(contentRef)" />
              </el-icon>
              <el-icon>
                <SwitchButton />
              </el-icon>
            </div>
          </div>

        </el-main>
      </el-container>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.training {
  .el-aside {
    height: 100vh;
    width: 28vw;
    min-width: 500px;

    .el-tab-pane {
      height: calc(100vh - 40px);
    }

    .editor {
      display: flex;
      flex-direction: column;
      height: calc(100% - 40px);
      overflow: hidden;
    }

    .footer {
      display: flex;
      position: absolute;
      bottom: 0;
      right: 12px;
      width: 100%;
      height: 40px;
      align-items: center;
      justify-content: flex-end;
    }
  }

  .content {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;

    .el-tab-pane {
      width: 100%;
      height: calc(100vh - 40px);
    }

    .toolbox {
      position: absolute;
      right: 0;
      top: 0;
      display: flex;
      height: 40px;
      padding: 0 20px;
      align-items: center;
      justify-content: space-between;
      background-color: #FFF;

      .el-icon {
        padding: 0 4px;

        svg {
          transition: all 0.5s;
        }

        &:hover svg {
          color: var(--bc-color-primary7)
        }
      }
    }
  }
}
</style>
